package com.heima.app.getway.filters;


import com.heima.app.getway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 认证过滤器
 * 没有令牌不让登录
 */
@Component
public class AuthFilters implements GlobalFilter, Ordered {

    /**
     * 执行过滤的方法
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //现获取请求队形和相应队像

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1判断是否是登录的请求
        if (request.getURI().getPath().contains("/login/login_auth")) {
            //2如果是登录的请求则放行

            return chain.filter(exchange);
        }

        //3.如果不是登录的请求，则从请求头中获取token
        String token = request.getHeaders().getFirst("token");
        //4.判断token是否有值

        if (token == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //5.若没有值则返回401
            return response.setComplete();
        }
        //6.若token有值 则判断token值是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i == 1 || i == 2) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED); //5.若没有值则返回401
            return response.setComplete();  //7无效 返回401
        }
        //8. 有效 放行

        return chain.filter(exchange);
    }

    /**
     * 过滤器优先级的方法
     *
     * @return
     */

    @Override
    public int getOrder() {
        return 0;
    }
}
